package com.dd.cloud.common.annotate.validation.impl;

import com.dd.cloud.common.annotate.validation.Card;
import com.dd.cloud.common.constants.RegularConstants;
import com.dd.cloud.common.utils.RegexUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 营业执照编号，纳税识别号，执业资格证编号，执业注册证编号，药材编号，采购单据编号验证实现类
 *
 * @author zk
 */
public class CardValidation implements ConstraintValidator<Card, Object> {
    private Card card;

    @Override
    public void initialize(Card cardVal) {
        card = cardVal;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String ph = (String) value;
        if (!card.required() && StringUtils.isBlank(ph)) {
            return true;
        }
        if (card.required() && StringUtils.isBlank(ph)) {
            return false;
        }
        //如果设置的返回的消息参数信息,则替换参数
        if (!StringUtils.isBlank(card.begin())){
            context.unwrap( HibernateConstraintValidatorContext.class ).addMessageParameter( "begin", card.begin() );
        }
        return RegexUtils.regCheck(ph, RegularConstants.NUM_REGEXP);
    }
}
